#!/bin/bash -e

function info() {
echo Usage: `basename $0` '[-d depth_filter] vcf'
exit 1
}

while getopts  ":p:f:i:d:" opt; do
	case  $opt  in
		p) out_prefix=$OPTARG;;
		f) suffix=$OPTARG;;
        i) bed=$OPTARG;;
        d) depth_filter=$OPTARG;;
		*) info;;
	esac
done
shift $(($OPTIND - 1))


if [ $# -lt 1 ]; then info; fi

. $var

vcf=$1
num_thread=8

depth_filter=${depth_filter:=5}

# bed1=$data/../data/adm/1_22.bed

# filter site
# filter within bed
# filter_vcf_bed.sh -p$out_prefix.bed $vcf $bed1

# echo; echo to bed
# java $j_mem -jar $gatk \
    # -R $ref_genome \
    # -T VariantsToBinaryPed \
    # -V variants.vcf \
    # -m metadata.fam \
    # -bed output.bed \
    # -bim output.bim \
    # -fam output.fam

echo generate .ped file
vcftools  --vcf  $vcf --plink --out $out_prefix

echo generate .bed
plink --file $out_prefix --make-bed --out $out_prefix


#------------------------------------------------

# filter conjucate? site


plink --file $out_prefix --indep-pairwise 1000 50 0.05 --out $out_prefix
# plink --file $out_prefix --extract $out_prefix.prune.in --out $out_prefix.filt_chain --make-bed --recode


:<<test

#------------------------------------------------


out_prefix=$out_prefix.filt_chain
cut -f1-2 $out_prefix.ped -d' ' |awk '{gsub("\.variant2?", "");print}' |tr a-z A-Z > $out_prefix.sample.list

awk '{gsub(/[0-9]+LANE[0-9]-/, ""); print}' $out_prefix.sample.list > $out_prefix.sample.list.1

cut -f3- $out_prefix.ped -d' ' > $out_prefix.ped.txt

paste -d' ' $out_prefix.sample.list.1 $out_prefix.ped.txt > $out_prefix.ped

awk 'BEGIN{OFS="\t"}{print $1, $1":"$4, "0", $4}' $out_prefix.map > $out_prefix.2.map


echo admixture
for k in `seq 4 9`; do
    admixture --cv -j$num_thread $out_prefix.bed $k > $out_prefix.$k.log
    sed -i 's/ /\t/g' $out_prefix.$k.Q
    paste $out_prefix.sample.list $out_prefix.$k.Q > $out_prefix.$k.q

    # str_sort=
    # for j in `seq 2 $k`; do
        # str_sort="$str_sort -k$j,${j}n"
    # done
    # sort $str_sort $out_prefix.$k.q > $out_prefix.$k.q.sort
    # q_bar.py -p$out_prefix.$k $out_prefix.$k.q.sort

    # q_bar.py -p$out_prefix.$k $out_prefix.$k.q $out_prefix.sample.list
    # q_bar1.py -p$out_prefix.$k $out_prefix.$k.q $out_prefix.sample.list
done

# admixture --cv -s time
test

. $cmd_done
